package com.example.barrage.config;

import com.example.barrage.handler.BarrageHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.logging.LogLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private BarrageHandler barrageHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // 添加Netty内置的日志处理器，用于调试
        pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
        
        // HTTP编解码器
        pipeline.addLast(new HttpServerCodec());
        // 块状写入处理器
        pipeline.addLast(new ChunkedWriteHandler());
        // HTTP对象聚合器，将HTTP消息聚合为FullHttpRequest/FullHttpResponse
        pipeline.addLast(new HttpObjectAggregator(65536));
        // WebSocket协议处理器，处理握手和协议升级
        // 添加更多日志以便调试握手过程
        pipeline.addLast(new WebSocketServerProtocolHandler("/barrage", null, true, 65536, false, true, 10000L));
        // 自定义弹幕处理器
        pipeline.addLast(barrageHandler);
    }
}